﻿using System;
using System.Web;
using System.Web.Mvc;

namespace Tecnosop.WebUI.Infrastructure.Notification
{
	public static class HtmlHelperExtensions
	{
		/// <summary>
		/// Render all messages that have been set during execution of the controller action.
		/// </summary>
		/// <param name="htmlHelper"></param>
		/// <returns></returns>
		public static HtmlString RenderMessages(this HtmlHelper htmlHelper)
		{
			var messages = String.Empty;
			foreach (var messageType in Enum.GetNames(typeof(MessageType)))
			{
				var message = htmlHelper.ViewContext.ViewData.ContainsKey(messageType)
								? htmlHelper.ViewContext.ViewData[messageType]
								: htmlHelper.ViewContext.TempData.ContainsKey(messageType)
									? htmlHelper.ViewContext.TempData[messageType]
									: null;
				if (message != null)
				{
                    var iconBoxBuilder = new TagBuilder("img");
                    iconBoxBuilder.MergeAttribute("style", "margin-top: 1px");
                    switch (messageType)
                    {
                        case "Success":
                            iconBoxBuilder.MergeAttribute("src", Links.Content.icons.ok_gif);
                            break;
                        case "Error":
                            iconBoxBuilder.MergeAttribute("src", Links.Content.icons.fail_gif);
                            break;
                        case "Warning":
                            iconBoxBuilder.MergeAttribute("src", Links.Content.icons.warn_gif);
                            break;
                        case "Info":
                            iconBoxBuilder.MergeAttribute("src", Links.Content.DefaultIcon._16x16.info_png);
                            break;
                        default:
                            break;
                    }

					var messageBoxBuilder = new TagBuilder("div");
                    messageBoxBuilder.InnerHtml += iconBoxBuilder.ToString();
                    messageBoxBuilder.AddCssClass("messagebox");
                    messageBoxBuilder.InnerHtml += message.ToString();

					messages += messageBoxBuilder.ToString();
				}
			}
			return MvcHtmlString.Create(messages);
		}
	}
}